package com.quanyan.ic.vendingMachine.remoting.impl;

import com.alibaba.fastjson.JSON;
import com.quanyan.ic.common.http.APIResponse;
import com.quanyan.ic.common.http.exception.BizException;
import com.quanyan.ic.vendingMachine.model.GoodsOperateRecord;
import com.quanyan.ic.vendingMachine.model.ReplenishmentInfo;
import com.quanyan.ic.vendingMachine.remoting.InventoryRemotingService;
import com.quanyan.ic.vendingMachine.remoting.request.PlaceGoodsInfo;
import com.quanyan.ic.vendingMachine.remoting.request.ReqPlaceOrder;
import com.quanyan.ic.vendingMachine.utils.HttpClientUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhuo.shi on 2017/8/2.
 */
@Service
public class InventoryRemotingServiceImpl implements InventoryRemotingService {

    public static final Logger logger = LoggerFactory.getLogger(InventoryRemotingServiceImpl.class);

    @Value("${place.server.url}")
    private String placeServiceUrl; //场馆服务地址
    private static final String batchUpdateGoodsInventory = "/admin/api/place/goods/batchUpdateGoodsInventory";     //批量更新库存接口
    private static final String insertGoodsOperateRecord = "/admin/api/place/goods/insertGoodsOperateRecord";        //库存操作记录接口

    /**
     * 调用场馆小商品批量更新库存服务
     */
    private void batchUpdateGoodsInventory(ReqPlaceOrder reqPlaceOrder) {
        String url = placeServiceUrl + batchUpdateGoodsInventory;
        String params = JSON.toJSONString(reqPlaceOrder);
        logger.info("call remote place inventory service, params={}", JSON.toJSONString(reqPlaceOrder));
        String respStr = null;
        APIResponse response = null;
        try {
            respStr = HttpClientUtils.postJson(url, params);
            logger.info("call remote place inventory service, return={}", respStr);
            response = JSON.parseObject(respStr, APIResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(respStr) || response == null || !response.isRet()) {
            logger.error("call remote place inventory service, failed, {}", (response != null ? JSON.toJSONString(response) : "null"));
            throw new BizException("更新库存失败" + (response != null ? response.getErrmsg() : ""));
        }
        logger.info("call remote place inventory service, ok, {}", JSON.toJSONString(response));
    }

    /**
     * 总库存中心，更新一种或多种商品库存
     *
     * @param placeId               场馆id
     * @param vmNumber              售货机编号
     * @param replenishmentInfoList 要更新的商品列表
     * @param input                 是否是入库
     */
    @Override
    public void updateGoodsCenterInventory(Integer placeId, String vmNumber, List<ReplenishmentInfo> replenishmentInfoList, boolean input) {
        if (placeId == null || StringUtils.isEmpty(vmNumber)
                || CollectionUtils.isEmpty(replenishmentInfoList)) {
            return;
        }
        ReqPlaceOrder req = new ReqPlaceOrder();
        req.setPlaceId(placeId);
        req.setSaleMachineNo(vmNumber);
        List<PlaceGoodsInfo> goodsInfoList = new ArrayList<>();
        for (ReplenishmentInfo replenishmentInfo : replenishmentInfoList) {
            PlaceGoodsInfo goodsInfo = new PlaceGoodsInfo();
            goodsInfo.setId(replenishmentInfo.getGoodsId());
            goodsInfo.setGoodsId(replenishmentInfo.getGoodsUuid());
            Integer rsptCount = replenishmentInfo.getRsptCount();
            if (rsptCount == 0) {
                continue;
            }
            if (!input) {
                rsptCount = -1 * rsptCount;  //出库
            }
            goodsInfo.setGoodsCount(rsptCount);
            goodsInfoList.add(goodsInfo);
        }
        req.setGoodsList(goodsInfoList);
        this.batchUpdateGoodsInventory(req);
    }

    /**
     * 总库存中心，记录库存变更记录
     *
     * @param record //售货机库存变更记录
     */
    @Override
    public void insertGoodsCenterOperateRecord(GoodsOperateRecord record) {

        String url = placeServiceUrl + insertGoodsOperateRecord;
        String params = JSON.toJSONString(record);
        String respStr = null;
        APIResponse response = null;
        logger.info("call remote service insertGoodsCenterOperateRecord: url={}, params={}", url, params);
        try {
            respStr = HttpClientUtils.postJson(url, params);
            logger.info("call remote service insertGoodsCenterOperateRecord: return, {}", respStr);
            response = JSON.parseObject(respStr, APIResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(respStr) || response == null || !response.isRet()) {
            logger.error("call remote service insertGoodsCenterOperateRecord failed");
            throw new BizException("中心库存操作记录失败" + (response != null ? response.getErrmsg() : ""));
        }
    }
}
